package com.travel.service.impl;

import cn.hutool.crypto.digest.BCrypt;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.travel.entity.dto.LoginRequestDTO;
import com.travel.entity.po.User;
import com.travel.entity.vo.LoginResponseVo;
import com.travel.exception.BusinessException;
import com.travel.mapper.UserMapper;
import com.travel.result.ResultCode;
import com.travel.service.AdminService;
import com.travel.utils.JWTUtil;
import org.springframework.stereotype.Service;

@Service
public class AdminServiceImpl implements AdminService {

    private final UserMapper userMapper;

    public AdminServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public LoginResponseVo login(LoginRequestDTO loginRequestDTO) {
        // 查询管理员用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", loginRequestDTO.getUsername())
                    .eq("user_status", 0); // 0表示管理员
        
        User admin = userMapper.selectOne(queryWrapper);
//        User admin = new User();
//        admin.setPassword("111111");
        // 验证用户是否存在
        if (admin == null) {
            throw new BusinessException(ResultCode.UNAUTHORIZED, "管理员账号不存在");
        }
        
        // 使用BCrypt验证密码
        if (!BCrypt.checkpw(loginRequestDTO.getPassword(), admin.getPassword())) {
            throw new BusinessException(ResultCode.UNAUTHORIZED, "密码错误");
        }
        
        // 生成JWT令牌
        String userJson = JSONObject.toJSONString(admin);
        JSONObject jsonObject = JSONObject.parseObject(userJson);
        jsonObject.remove("password");
        userJson = jsonObject.toJSONString();
        String token = JWTUtil.generateToken(userJson);
        
        // 更新最后登录时间
        admin.setLastLogin(new java.util.Date());
        userMapper.updateById(admin);
        
        // 构建返回对象
        LoginResponseVo loginResponseDTO = new LoginResponseVo();
        loginResponseDTO.setUsername(admin.getUsername());
        loginResponseDTO.setToken(token);
        
        return loginResponseDTO;
    }
} 